package com.suse.forum.controller;


import com.suse.forum.common.AppResult;
import com.suse.forum.common.ResultCode;
import com.suse.forum.config.AppConfig;
import com.suse.forum.model.Article;
import com.suse.forum.model.Board;
import com.suse.forum.model.User;
import com.suse.forum.service.IArticleService;
import com.suse.forum.service.IBoardService;
import com.suse.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@Api(tags = "文章接口")
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    @Value("${httpUrl}")
    private String httpUrl;

    /**
     *  发布新帖子
     * @param boardId 板块ID
     * @param title  文章标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块ID")@RequestParam("boardId")@NonNull long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @RequestParam("imgs") @NonNull String imgs,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        // 校验用户是否禁言
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            // 用户已被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 板块的校验
        Board board = boardService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.info(ResultCode.FAILED_BOARD_BANNED.toString());
            //返回响应
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setImgs(imgs); // 标题
        article.setTitle(title); // 标题
        article.setContent(content); // 正文
        article.setBoardId(boardId); // 板块ID
        article.setUserId(user.getId()); // 作者ID

        // 调用service层方法
        articleService.create(article);
        // 响应成功
        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块ID") @RequestParam(value = "boardId",required = false) Long boardId) {
        //定义返回的集合
        List<Article> articles = null;
        if(boardId == null) {
            // 查询所有
            articles = articleService.selectAll();
        }else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        //  结果是否为空
        if(articles == null) {
            // 如果结果集为空，则创建一个空集合
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }

    @ApiOperation("根据帖子ID获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request, @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        // 从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 根据ID查询帖子详情
        Article article = articleService.selectDetailById(id);
        // 判断结果是否为空
        if(article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前用户是否是作者
        if(user.getId() == article.getUserId()) {
            //标识为作者
            article.setOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify (HttpServletRequest request,
                             @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id,
                             @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                             @RequestParam("imgs") @NonNull String imgs,
                             @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
        // 从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 校验用户状态
        if(user.getState() == 1) {
            // 用户已被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 根据ID查询帖子详情
        Article article = articleService.selectById(id);
        // 判断结果是否为空
        if(article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前用户是否是作者
        if(user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 判断帖子的状态
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 调用sevice
        articleService.modify(id, title, content,imgs);
        log.info("修改帖子成功，帖子ID：{}", id + ", 修改人ID：" + user.getId());
        // 响应成功
        return AppResult.success();
    }

    @ApiOperation("修改点赞数")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request, @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        // 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            // 用户已被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 调用service
        articleService.thumbsUpById(id);
        // 响应成功
        return  AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request, @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id) {
        // 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            // 用户已被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 判断结果是否为空
        if(article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断当前用户是否是作者
        if(user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用service
        articleService.deleteById(id);
        // 响应成功
        return AppResult.success();
    }

    @GetMapping("/getAllByUserId")
    @ApiOperation("获取用户的帖子列表")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request, @ApiParam("用户Id") @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，则从session中获取当前登录的用户ID
        if(userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用service
        List<Article> list = articleService.selectByUserId(userId);
        // 响应成功
        return AppResult.success(list);
    }

    @Value("${imgPath}")
    private String imgPath;

    @PostMapping("upload")
    public Map upoadFile(@RequestParam("editormd-image-file") MultipartFile upload){

        String fileName = UUIDUtil.UUID_32();


        String oldName = upload.getOriginalFilename();
        String extension = oldName.substring(oldName.lastIndexOf("."));
        File file = new File(imgPath + "/" + fileName + extension);
        if(!file.exists()){
            file.mkdirs();
        }
        Map result = new HashMap();
//        File newFile = new File(imgPath + "/" + fileName);
        try {

            upload.transferTo(file);
            log.info("上传文件路径-----------------{}", file.getAbsoluteFile());


            result.put("success", 1);
            result.put("message", "上传成功");
            result.put("url", httpUrl + file.getName());
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", 0);
            result.put("message", "上传失败");
        }

        return result;

    }

}
